package netty.im.server;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.util.Map;

import org.apache.log4j.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.concurrent.GlobalEventExecutor;
import netty.im.util.RequestParser;

public class SimpleChatServerHandler extends SimpleChannelInboundHandler<HttpObject> { // (1)

	public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	
	private HttpRequest request;

	private static Logger log = Logger.getLogger(SimpleChatServerHandler.class);

	/*@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // (2)
		Channel incoming = ctx.channel();
		for (Channel channel : channels) {
			channel.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 加入\n");
		}
		channels.add(ctx.channel());
	}*/

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // (3)
		Channel incoming = ctx.channel();
		for (Channel channel : channels) {
			channel.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 离开\n");
		}
		channels.remove(ctx.channel());
	}

/*	protected void messageReceived(ChannelHandlerContext ctx, String s) throws Exception { // (4)
		Channel incoming = ctx.channel();

		JSONObject json = JSON.parseObject(s);
		// 客户端请求连接
		if("conn".equals(json.getString("action"))) {
			// 当前的连接加入到map中
			NettyChannelMap.add(json.getString("id"), (SocketChannel) ctx.channel());
			log.info(json.getString("usr") + "---连接成功");
			BackConnectMsgRespVO backConnectMsgRespVO = new BackConnectMsgRespVO();
			backConnectMsgRespVO.setId(ctx.channel().id().toString());
			backConnectMsgRespVO.setAction("conn");
			backConnectMsgRespVO.setIps("" + incoming.remoteAddress());
			backConnectMsgRespVO.setRar(null);
			backConnectMsgRespVO.setSsl(null);
			String text = JSON.toJSONString(backConnectMsgRespVO);
			// 返回的成功消息
			incoming.writeAndFlush(text);
		}

		
		// channel.writeAndFlush("[you]" + s + "\n");

	}*/

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
		Channel incoming = ctx.channel();
		// System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"在线");
		log.info("SimpleChatClient:" + incoming.remoteAddress() + "在线");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
		Channel incoming = ctx.channel();
		// System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"掉线");
		NettyChannelMap.remove((SocketChannel) ctx.channel());
		log.info("SimpleChatClient:" + incoming.remoteAddress() + "掉线");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
		Channel incoming = ctx.channel();
		// System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"异常");
		log.info("SimpleChatClient:" + incoming.remoteAddress() + "异常");
		// 当出现异常就关闭连接
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
		
		if (msg instanceof HttpRequest) {
            request = (HttpRequest) msg;
    		Map<String, String> parmMap = new RequestParser(request).parse(); // 将GET, POST所有请求参数转换成Map对象
            String uri = request.uri();
            System.out.println("Uri:" + uri);
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf buf = content.content();
            System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
            buf.release();

            String res = "OK";
            NettyChannelMap.add("100", (SocketChannel) ctx.channel());
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
            response.headers().set("Content-Type", "text/plain");
            response.headers().setInt("Content-Length",response.content().readableBytes());
          /*  if (HttpHeaders.isKeepAlive(request)) {
                response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            }*/
            NettyChannelMap.get("100").writeAndFlush(res);
            ctx.write(response);
            ctx.flush();
        }
		
	}

}
